﻿using System;
using System.IO;
using System.Reflection;
using FileDistributor.Configuration;
using FileDistributor.IO;
using FileDistributor.Notification;
using log4net;

namespace FileDistributor.FileTransfer
{
    public static class FtpUploadEventHandler
    {
        private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static readonly FileDistributorSection _configSection = ConfigurationHelper.GetDistributorSection();

        public static void HandleSuccessEvent(object sender, FtpUploadEventArgs e)
        {
            _logger.Info("File uploaded successfully");

            var fileManager = new FileManager();
            fileManager.MoveFile(e.State.SourcePath, ProgressState.Success);
        }

        public static void HandleFailureEvent(object sender, FtpUploadEventArgs e)
        {
            _logger.Error("Failed to upload file", e.State.OperationException);
            
            var fileManager = new FileManager();
            var filePath = fileManager.MoveFile(e.State.SourcePath, ProgressState.Failure);

            SendFailureNotification(e, filePath);
        }

        private static void SendFailureNotification(FtpUploadEventArgs e, string filePath)
        {
            var from = _configSection.MailNotification.From;
            var to = _configSection.MailNotification.To;
            var subject = _configSection.MailNotification.Subject;
            var fileName = Path.GetFileName(e.State.SourcePath);

            var message = _configSection.MailNotification.Message;
            message += Environment.NewLine;
            message += Environment.NewLine;
            message += "Filnamn: " + fileName + ",  ftpadress: " + e.State.TargetUri;
            message += Environment.NewLine;
            message += Environment.NewLine;
            message += e.State.OperationException;

            var mailSender = new MailSender();

            if (to.Contains(","))
            {
                var toAdresses = to.Split(',');
                foreach (var toAdress in toAdresses)
                {
                    
                    mailSender.SendMail(from, toAdress, subject, message, filePath);
                }
            }
            else
            {
                mailSender.SendMail(from, to, subject, message, filePath);
            }
        }
    }
}
